package cn.org.donald.framework.handler;

import cn.org.donald.framework.constant.TableConstant;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import cn.org.donald.framework.pojo.dto.LoginUser;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * @author ： Donald
 * @date ： 2020/10/24 23:00
 * @description：
 */
@Configuration
public class MybatisPlusHandler implements MetaObjectHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("filling in field: {}","insert");
        fillCreate(metaObject);
        fillModify(metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        logger.info("filling in field: {}","update");
        fillModify(metaObject);
    }

    private void fillModify(MetaObject metaObject){
        this.setFieldValByName(TableConstant.FIELD_MODIFIED_BY,getUserId(),metaObject);
        this.setFieldValByName(TableConstant.FIELD_MODIFIER,getUserName(),metaObject);
        this.setFieldValByName(TableConstant.FIELD_GMT_MODIFIED,new Date(),metaObject);
    }

    private void fillCreate(MetaObject metaObject){
        this.setFieldValByName(TableConstant.FIELD_CREATED_BY,getUserId(),metaObject);
        this.setFieldValByName(TableConstant.FIELD_CREATOR,getUserName(),metaObject);
        this.setFieldValByName(TableConstant.FIELD_GMT_CREATED,new Date(),metaObject);
    }

    private Long getUserId(){
        Subject subject = SecurityUtils.getSubject();

        Long userId = TableConstant.VALUE_ADMIN_USER_ID;
        try {
            LoginUser loginUser = (LoginUser) subject.getPrincipal();
            userId = loginUser.getUserId()==null?userId:loginUser.getUserId();
        }catch (Exception e){
            logger.warn("自动填充:{}","获取不到用户信息");
        }
        return userId;
    }

    private String getUserName() {
        Subject subject = SecurityUtils.getSubject();
        String userName = TableConstant.VALUE_ADMIN_USER_NAME;
        try {
            LoginUser loginUser = (LoginUser) subject.getPrincipal();
            userName = loginUser.getUserName()==null?userName:loginUser.getUserName();
        }catch (Exception e){
            logger.warn("自动填充:{}","获取不到用户信息");
        }
        return userName;
    }


}
